package algorithm.action;

public class GetNumberOfK {

	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,7};
		int k = 7;
		System.out.println(getNumberOfK(arr, k));
		
	}
	
	static int getNumberOfK(int[] arr, int k) {
		if(arr == null || arr.length == 0) return 0;
		int l = 0, r = arr.length-1;
		int div = l;
		while(l <= r) {
			div = (l+r) >> 1;
			if(arr[div] == k) break;
			else if(arr[div] > k) r = div-1;
			else l = div+1;
		}
		if(l > r) return 0;
		int count = 0;
		for(int i = div; i < arr.length; i++) {
			if(arr[i] != k) break;
			else count ++;
		}
		for(int j = div-1; j >= 0; j--) {
			if(arr[j] != k) break;
			else count ++;
		}
		return count;
	}
}
